var express = require('express');
var router = express.Router();
var request = require('../db/mssql')
var QcloudSms = require("qcloudsms_js");
// var { v4: uuidv4 } = require('uuid')
var jwt = require('jsonwebtoken');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

//首页-推荐
router.get('/api/indexList/1/data/1', function (req, res, next) {
  res.send({
    code: 200,
    data: {
      lyTabs: [
        { title: "推荐", name: 1 },
        { title: "金骏眉", name: 2 },
        { title: "大红袍", name: 3 },
        { title: "铁观音", name: 4 },
        { title: "绿茶", name: 5 },
        { title: "黑茶", name: 6 },
        { title: "普洱", name: 7 },
        { title: "正山小种", name: 8 },
        { title: "茉莉花茶", name: 9 },
        { title: "茶具", name: 10 },
      ],
      data: [
        {
          id: 0,
          type: 'swiperList',
          data: [
            {
              id: 1,
              imgUrl: "./images/swiper1.jpeg",
            },
            {
              id: 2,
              imgUrl: "./images/swiper2.jpeg",
            },
            {
              id: 3,
              imgUrl: "./images/swiper3.jpeg",
            },
          ]
        },
        {
          id: 1,
          type: 'iconList',
          data: [
            {
              id: 1,
              title: "自饮茶",
              imgUrl: "./images/icons1.png",
            },
            {
              id: 2,
              title: "茶具",
              imgUrl: "./images/icons2.png",
            },
            {
              id: 3,
              title: "茶礼盒",
              imgUrl: "./images/icons3.png",
            },
            {
              id: 4,
              title: "领福利",
              imgUrl: "./images/icons4.png",
            },
            {
              id: 5,
              title: "官方验证",
              imgUrl: "./images/icons5.png",
            },
          ]
        },
        {
          id: 2,
          type: 'recommendList',
          data: [
            {
              id: 1,
              imgUrl: "./images/recommend.jpeg",
              name: "龙井1號铁罐250g",
              content: "鲜爽甘醇 口粮首选",
              price: 68,
            },
            {
              id: 2,
              imgUrl: "./images/recommend.jpeg",
              name: "铁观音2號250g",
              content: "核心产区滋味正",
              price: 128,
            },
            {
              id: 3,
              imgUrl: "./images/recommend.jpeg",
              name: "铁观音2號250g",
              content: "核心产区滋味正",
              price: 88,
            },
          ]
        },
        {
          id: 3,
          type: 'likeList',
          data: [
            {
              id: 1,
              name: "建盏茶具套装 红色芝麻毫 12件套",
              price: "399",
              imgUrl: "./images/like.jpeg",
            },
            {
              id: 2,
              name: "旅行茶具 快客旅行套装",
              price: "288",
              imgUrl: "./images/like2.jpeg",
            },
            {
              id: 3,
              name: "茶具套组 乌金石",
              price: "177",
              imgUrl: "./images/like3.jpeg",
            },
          ]
        },
      ]
    }
  })
})

//首页-大红袍
router.get('/api/indexList/3/data/1', function (req, res, next) {
  res.send({
    code: 200,
    data: {
      lyTabs: [
        { title: "推荐", name: 1 },
        { title: "金骏眉", name: 2 },
        { title: "大红袍", name: 3 },
        { title: "铁观音", name: 4 },
        { title: "绿茶", name: 5 },
        { title: "黑茶", name: 6 },
        { title: "普洱", name: 7 },
        { title: "正山小种", name: 8 },
        { title: "茉莉花茶", name: 9 },
        { title: "茶具", name: 10 },
      ],
      data: [
        {
          id: 1,
          type: 'ad',
          data: {
            imgUrl: "./images/dhp.jpeg",
          }
        },
        {
          id: 2,
          type: 'likeList',
          data: [
            {
              id: 1,
              name: "建盏茶具套装 红色芝麻毫 12件套",
              price: "399",
              imgUrl: "./images/like.jpeg",
            },
            {
              id: 2,
              name: "旅行茶具 快客旅行套装",
              price: "288",
              imgUrl: "./images/like2.jpeg",
            },
            {
              id: 3,
              name: "茶具套组 乌金石",
              price: "177",
              imgUrl: "./images/like3.jpeg",
            },
          ]
        },
      ]
    }
  })
})

//首页-铁观音
router.get('/api/indexList/4/data/1', function (req, res, next) {
  res.send({
    code: 200,
    data: {
      lyTabs: [
        { title: "推荐", name: 1 },
        { title: "金骏眉", name: 2 },
        { title: "大红袍", name: 3 },
        { title: "铁观音", name: 4 },
        { title: "绿茶", name: 5 },
        { title: "黑茶", name: 6 },
        { title: "普洱", name: 7 },
        { title: "正山小种", name: 8 },
        { title: "茉莉花茶", name: 9 },
        { title: "茶具", name: 10 },
      ],
      data: [
        {
          id: 1,
          type: 'ad',
          data: {
            imgUrl: "./images/tgy.jpeg",
          }
        },
        {
          id: 2,
          type: 'likeList',
          data: [
            {
              id: 1,
              name: "建盏茶具套装 红色芝麻毫 12件套",
              price: "399",
              imgUrl: "./images/like.jpeg",
            },
            {
              id: 2,
              name: "旅行茶具 快客旅行套装",
              price: "288",
              imgUrl: "./images/like2.jpeg",
            },
            {
              id: 3,
              name: "茶具套组 乌金石",
              price: "177",
              imgUrl: "./images/like3.jpeg",
            },
          ]
        },
      ]
    }
  })
})

//关键字模糊搜索
router.get('/api/search/searchList', (req, res, next) => {
  //查询条件
  let { keyword, sortKey, orderBy } = req.query;
  let sql = `select * from goods_list where title like '%${keyword}%'`;
  if (sortKey && orderBy) {
    sql += ` order by ${sortKey} ${orderBy}`;
  }
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    res.send({
      code: 200,
      data: result.recordset
    })
  });
})

//分类
router.get('/api/categoryList', (req, res, next) => {
  res.send({
    code: 200,
    data: {
      adImgUrl: './images/list-ad.jpeg',
      data: [
        {
          id: 1,
          name: '推荐',
          data: [
            {
              id: 1,
              name: '推荐',
              list: [
                {
                  id: 0,
                  name: '紫砂壶',
                  imgUrl: './images/list0.jpeg',
                },
                {
                  id: 1,
                  name: '铁观音',
                  imgUrl: './images/list1.jpeg',
                },
                {
                  id: 2,
                  name: '金骏眉',
                  imgUrl: './images/list2.jpeg',
                },
                {
                  id: 3,
                  name: '武夷岩茶',
                  imgUrl: './images/list3.jpeg',
                },
                {
                  id: 4,
                  name: '龙井',
                  imgUrl: './images/list4.jpeg',
                },
                {
                  id: 5,
                  name: '云南滇红',
                  imgUrl: './images/list5.jpeg',
                },
                {
                  id: 6,
                  name: '建盏',
                  imgUrl: './images/list6.jpeg',
                },
                {
                  id: 7,
                  name: '功夫茶具',
                  imgUrl: './images/list7.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 2,
          name: '新品',
          data: [
            {
              id: 1,
              name: '新品',
              list: [
                {
                  id: 0,
                  name: '五月新品',
                  imgUrl: './images/list8.jpeg',
                },
                {
                  id: 1,
                  name: '六月新品',
                  imgUrl: './images/list9.png',
                },
              ]
            }
          ]
        },
        {
          id: 3,
          name: '习茶',
          data: [
            {
              id: 1,
              name: '习茶',
              list: [
                {
                  id: 0,
                  name: '习茶',
                  imgUrl: './images/list10.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 4,
          name: '绿茶',
          data: [
            {
              id: 1,
              name: '绿茶',
              list: [
                {
                  id: 0,
                  name: '龙井',
                  imgUrl: './images/list4.jpeg',
                },
                {
                  id: 1,
                  name: '黄山毛峰',
                  imgUrl: './images/list11.jpeg',
                },
                {
                  id: 2,
                  name: '碧螺春',
                  imgUrl: './images/list12.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 5,
          name: '乌龙',
          data: [
            {
              id: 1,
              name: '乌龙',
              list: [
                {
                  id: 1,
                  name: '铁观音',
                  imgUrl: './images/list1.jpeg',
                },
                {
                  id: 2,
                  name: '漳平水仙',
                  imgUrl: './images/list13.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 6,
          name: '红茶',
          data: [
            {
              id: 1,
              name: '红茶',
              list: [
                {
                  id: 1,
                  name: '金骏眉',
                  imgUrl: './images/list2.jpeg',
                },
                {
                  id: 2,
                  name: '正山小种',
                  imgUrl: './images/list14.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 7,
          name: '白茶',
          data: [
            {
              id: 1,
              name: '白茶',
              list: [
                {
                  id: 1,
                  name: '白牡丹',
                  imgUrl: './images/list15.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 8,
          name: '普洱',
          data: [
            {
              id: 1,
              name: '普洱',
              list: [
                {
                  id: 1,
                  name: '生茶',
                  imgUrl: './images/list16.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 9,
          name: '花茶',
          data: [
            {
              id: 1,
              name: '花茶',
              list: [
                {
                  id: 1,
                  name: '茉莉花茶',
                  imgUrl: './images/list17.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 10,
          name: '茶具',
          data: [
            {
              id: 1,
              name: '茶具',
              list: [
                {
                  id: 1,
                  name: '茶宠',
                  imgUrl: './images/list18.jpeg',
                },
              ]
            }
          ]
        },
        {
          id: 11,
          name: '手艺',
          data: [
            {
              id: 1,
              name: '手艺',
              list: [
                {
                  id: 1,
                  name: '根雕',
                  imgUrl: './images/list19.png',
                },
              ]
            }
          ]
        },
      ]
    }
  })
})


//根据id查找商品信息
router.get('/api/good/getGoodById', (req, res, next) => {
  //查询条件
  let id = req.query.id;
  let sql = `select * from goods_list where id = '${id}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    res.send({
      code: 200,
      data: result.recordset[0]
    })
  });
})

//密码登录
router.post('/api/login', (req, res, next) => {
  //查询条件
  let { userTel, userPwd } = req.query;
  let sql = `select * from sys_user where tel = '${userTel}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    let data = result.recordset[0];
    let code = 200;
    if (data) {
      if (data.pwd != userPwd) {
        code = 301;
        data = '密码不正确';
      }
      // else {
      //   data = data.token;
      // }
    } else {
      code = 301;
      data = '手机号不存在';
    }
    res.send({
      code,
      data
    })
  });
})

//验证码
router.get('/api/getVerificationCode', (req, res, next) => {
  //https://github.com/qcloudsms/qcloudsms_js

  var tel = req.body.userTel;

  //tips:先注册腾讯云

  // 短信应用SDK AppID
  var appid = 1400187558;  // SDK AppID是1400开头
  // 短信应用SDK AppKey
  var appkey = "dc9dc3391896235ddc2325685047edc7";
  // 需要发送短信的手机号码
  var phoneNumbers = [tel];
  // 短信模板ID，需要在短信应用中申请
  var templateId = 285590;  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
  // 签名
  var smsSign = "三人行慕课";  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`
  // 实例化QcloudSms
  var qcloudsms = QcloudSms(appid, appkey);
  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback(err, ress, resData) {
    if (err) {
      console.log("err: ", err);
    } else {
      console.log("request data: ", ress.req);
      console.log("response data: ", resData);
      res.send({
        code: 200,
        data: ress.req.body.params[0] //测试用来返回，避免验证真实手机号
      })
    }
  }

  var ssender = qcloudsms.SmsSingleSender();
  //随机四位整数
  var randnum = Math.floor(Math.random() * (9999 - 1000)) + 1000;
  var params = [randnum];
  ssender.sendWithParam(86, phoneNumbers[0], templateId,
    params, smsSign, "", "", callback);  // 签名参数不能为空串
})

//验证码登录 - 注册/存储用户信息
router.post('/api/saveUser', (req, res, next) => {
  //查询条件
  let tel = req.query.tel;

  let sql = `select * from sys_user where tel = '${tel}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    let data = result.recordset[0];
    if (data) {
      res.send({
        code: 200,
        data
      })
    } else {
      //不存在就注册
      // var token = uuidv4();
      // var token = jwt.sign(用户信息, 口令);
      var token = jwt.sign({ tel: tel }, 'teatea');
      var insertsql = `insert into sys_user(tel,pwd,name,token,imgUrl)values('${tel}','123456','${tel}','${token}','./images/default_head.png')`;
      request(insertsql, function (err, resultt) {
        if (err) {
          console.error(err);
          return;
        }

        let sql = `select * from sys_user where tel = '${tel}'`;
        request(sql, function (err, resulttt) {
          if (err) {
            console.error(err);
            return;
          }
          res.send({
            code: 200,
            data: resulttt.recordset[0]
          })
        })
      })
    }
  });
})

//注册
router.post('/api/registerUser', (req, res, next) => {
  //查询条件
  let { tel, pwd } = req.body;
  let sql = `select * from sys_user where tel = '${tel}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    let data = result.recordset[0];
    if (data) {
      //手机号已注册过，提醒...
      res.send({
        success: false,
        msg: '该手机号已被注册，请直接登录'
      })
    } else {
      //不存在就注册
      // var token = uuidv4();
      var token = jwt.sign({ tel: tel }, 'teatea');
      var insertsql = `insert into sys_user(tel,pwd,name,token,imgUrl)values('${tel}','${pwd}','${tel}','${token}','./images/default_head.png')`;
      request(insertsql, function (err, resultt) {
        if (err) {
          console.error(err);
          return;
        }
        let sql = `select * from sys_user where tel = '${tel}'`;
        request(sql, function (err, resulttt) {
          if (err) {
            console.error(err);
            return;
          }
          res.send({
            success: true,
            code: 200,
            data: resulttt.recordset[0]
          })
        })
      })
    }
  });
})

//检测用户是否存在
router.post('/api/checkUser', (req, res, next) => {
  //查询条件
  let tel = req.query.tel;
  let sql = `select * from sys_user where tel = '${tel}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    let data = result.recordset[0];
    let success = false, msg = '';
    if (data) {
      success = true;
    } else {
      msg = '该手机号未注册过';
    }
    res.send({
      success,
      msg
    })
  });
})

//修改密码
router.post('/api/changePwd', (req, res, next) => {
  //查询条件
  let { tel, pwd } = req.body;
  let sql = `update sys_user set pwd = '${pwd}' where tel = '${tel}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    res.send({
      code: 200
    })
  });
})

//加入购物车
router.post('/api/addCart', (req, res, next) => {
  //查询条件
  let token = req.headers.token;
  let tel = jwt.decode(token).tel;
  let { goods_id, qty } = req.body;

  let sql = `select * from cart_list where user_tel = '${tel}' and goods_id = '${goods_id}'`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    let data = result.recordset[0];
    //存在更新，数量+1；不存在插入，数量为1
    if (data) {
      let sql = `update cart_list set qty = qty+${qty} where id = '${data.id}'`;
      request(sql, function (err, result) {
        if (err) {
          console.error(err);
          return;
        }
        res.send({
          code: 200
        })
      });
    } else {
      let sql = `insert into cart_list(user_tel, goods_id, qty) values('${tel}','${goods_id}','${qty}')`;
      request(sql, function (err, result) {
        if (err) {
          console.error(err);
          return;
        }
        res.send({
          code: 200
        })
      });
    }
  });
})

//购物车列表
router.get('/api/cartList', (req, res, next) => {
  //查询条件
  let token = req.headers.token;
  let tel = jwt.decode(token).tel;
  let sql = `SELECT t1.id cart_id
                    ,t1.user_tel
                    ,t1.goods_id
                    ,t1.qty
                    ,t2.title
                    ,t2.details
                    ,t2.price
                    ,t2.num
                    ,t2.wt
                    ,t2.imgUrl
                  FROM   cart_list t1
                    LEFT JOIN goods_list t2
                            ON t1.goods_id = t2.id
                  WHERE  t1.user_tel = '${tel}' `;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    res.send({
      code: 200,
      data: result.recordset
    })
  });
})

//移除购物车项
router.post('/api/removeCart', (req, res, next) => {
  //查询条件
  let token = req.headers.token;
  let tel = jwt.decode(token).tel;
  let cart_id = req.body;
  let ids = ''
  cart_id.forEach(a => {
    ids += `${a},`
  });
  ids = ids.slice(0, ids.length - 1);
  let sql = `delete from cart_list where user_tel = '${tel}' and id in (${ids})`;
  request(sql, function (err, result) {
    if (err) {
      console.error(err);
      return;
    }
    res.send({
      code: 200
    })
  });
})

module.exports = router;
